﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper.Internal.Mappers;
using static Volo.Abp.Identity.Settings.IdentitySettingNames;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Application.Services;
using ERP.RBAC.Dto;

namespace ERP.RBAC
{
    public class UserServices : ApplicationService, IUserServices
    {
        /// <summary>
        /// 用户仓储
        /// </summary>
        private readonly IRepository<Users, int> _userServices;

        public UserServices(IRepository<Users, int> userServices)
        {
            _userServices = userServices;
        }

        public async Task<int> AddUser(UserDTO user)
        {
            var useradd = ObjectMapper.Map<UserDTO, Users>(user);
            var usercount = await _userServices.InsertAsync(useradd);
            return usercount == null ? 0 : 1;

        }

        public async Task<int> DeleteUser(int userId)
        {
            try
            {
                var user = await _userServices.FindAsync(m => m.Id == userId);
                if (user == null)
                {
                    return 0;
                }
                await _userServices.DeleteAsync(user);
                return 1;
            }
            catch
            {
                return 0;
            }
        }

        public async Task<UserDTO> GetUser(int userId)
        {
            var user = await _userServices.FindAsync(m => m.Id == userId);
            var result = ObjectMapper.Map<Users, UserDTO>(user);
            return result;

        }

        public async Task<List<UserDTO>> ShowUser()
        {
            var userList = await _userServices.GetListAsync();
            var result = ObjectMapper.Map<List<Users>, List<UserDTO>>(userList.OrderByDescending(m=>m.Id).ToList());
            return result;
        }

        public async Task<int> UpdateUser(UserDTO user)
        {
            var useradd = ObjectMapper.Map<UserDTO, Users>(user);
            var usercount = await _userServices.UpdateAsync(useradd);
            return usercount == null ? 0 : 1;
        }
    }
}
